package logic

import (
	"context"
	"login-guard/loginrpc/internal/svc"
	"login-guard/loginrpc/loginrpc"
	"login-guard/models/cache"
	"login-guard/models/mysql"
	"login-guard/pkg"
	"strconv"
	"time"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.Login
	redis_key := "user" + strconv.Itoa(int(user.ID))
	cacheUser, _ := cache.Rdb.Get(l.ctx, redis_key).Int()
	if cacheUser >= 3 {
		return nil, errors.New("密码错误3次，禁止登录")
	}
	//短信验证码
	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != "" {
		return nil, errors.New("短信验证码错误")
	}
	//图形验证码
	result2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result2 != "" {
		return nil, errors.New("图形验证码错误")
	}
	if err := user.FindLoginByAccount(mysql.DB, in.Account); err != nil {
		user = mysql.Login{
			Account:  in.Account,
			Password: pkg.Md5(in.Password),
		}

		if err = user.UserCreate(mysql.DB); err != nil {
			return nil, errors.New("用户添加失败")
		}
	}
	if user.Password != pkg.Md5(in.Password) {
		cache.Rdb.Incr(l.ctx, redis_key)
		if cacheUser == 2 {
			cache.Rdb.Set(l.ctx, redis_key, 3, time.Hour*3)
			return nil, errors.New("密码错误3次，封禁2小时")
		}
		return nil, errors.New("密码错误")
	}
	//cache.Rdb.Del(l.ctx, "SendSms"+in.Account)
	return &loginrpc.LoginResponse{
		UserId: int64(int(user.ID)),
	}, nil
}
